package com.open.library.network;

import android.content.Context;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;

import com.open.library.joor.Reflect;

/**
 * 网络模块(包括热点，有线 自动/手动 切换等等)
 *
 * @Author: hailong.qiu
 * @Maintainer: hailong.qiu
 * @Date: 2018.03.26
 * @Copyright: 2018   Inc. All rights reserved.
 */
public class NetWorkTools {

    public static final int WIFI_AP_STATE_ENABLED = 13;
    public static final int WIFI_AP_STATE_ENABLING = 12;
    public static final int WIFI_AP_STATE_DISABLED = 11;
    public static final int WIFI_AP_STATE_DISABLING = 10;

    public static final int WIFI_AP_STATE_FAILED = 14;

    public static class KeyMgmt {
        public static final int WPA2_PSK = 4;
    }

    private Context mContext;
    private WifiManager mWifiManager;
    private WifiManagerRef mWifiManagerRef;

    public NetWorkTools(Context context) {
        mContext = context;
        mWifiManager=(WifiManager)context.getSystemService(Context.WIFI_SERVICE);
        mWifiManagerRef = new WifiManagerRef(mContext);
    }

    /**
     * 设置 WIFI热点配置.
     */
    public void setWifiApConfig(String ssid, String pwd) {
        WifiConfiguration config = new WifiConfiguration();
        config.allowedKeyManagement.set(KeyMgmt.WPA2_PSK);
        config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
        config.SSID = ssid;
        config.preSharedKey = pwd;

//        closeWifi();

        int apState = getWifiApState(); /* mWifiManager.getWifiApState(); */
        if (WIFI_AP_STATE_ENABLED == apState) {
            // restart wifiap
            setWifiApEnabled(null, false);
            setWifiApEnabled(config, true);
        } else {
            setWifiApEnabled(null, true);
            setWifiApConfiguration(config); /* mWifiManager.setWifiApConfiguration(config); */
        }
    }

    /**
     * mWifiManager.setWifiApConfiguration(config);
     */
    private void setWifiApConfiguration(WifiConfiguration config) {
        mWifiManagerRef.setWifiApConfiguration(config);
    }

    /**
     * mWifiManager.getWifiApState();
     */
    private int getWifiApState() {
        return mWifiManagerRef.getWifiApState();
    }

    /**
     * 设置WIFI热点.
     */
    private void setWifiApEnabled(final WifiConfiguration wifiConfiguration, final boolean enable) {
        mWifiManagerRef.setWifiApEnabled(wifiConfiguration, enable);
    }

}
